package com.encyclopedia.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.encyclopedia.entity.Document;
import com.encyclopedia.mapper.DocumentMapper;
import com.encyclopedia.result.exception.ServiceException;
import com.encyclopedia.result.exenum.RequestException;
import com.encyclopedia.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文献业务层
 *
 * @author by 春风能解释
 * <p>
 * 2024/5/1
 */
@Service
@Transactional
@Slf4j
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, Document> implements DocumentService {

    /**
     * 数据层注入
     */
    @Autowired
    private DocumentMapper documentMapper;

    /**
     * 条件检索文献信息
     *
     * @param current  页码
     * @param size     页长
     * @param document 条件
     * @return 列表
     */
    @Override
    public IPage<Document> pageDocument(Integer current, Integer size, Document document) {
        IPage<Document> documentIPage = documentMapper.pageDocument(new Page<>(current, size), document);
        if (documentIPage.getSize() == 0) {
            throw new ServiceException(RequestException.NOT_FOUND);
        }
        return documentIPage;
    }

    /**
     * 新增一条文献信息
     *
     * @param document 文献信息
     * @return 影响行数
     */
    @Override
    public Integer insertOneDocument(Document document) {
        int column = documentMapper.insert(document);
        if (column < 1) {
            throw new ServiceException(RequestException.INSERT_ERROR);
        }
        return column;
    }

    /**
     * 更新一条文献信息
     *
     * @param document 文献信息
     * @return 影响行数
     */
    @Override
    public Integer updateOneDocument(Document document) {
        int column = documentMapper.updateById(document);
        if (column < 1) {
            throw new ServiceException(RequestException.UPDATE_ERROR);
        }
        return column;
    }

    /**
     * 批量删除文献信息
     *
     * @param ids id
     * @return 影响行数
     */
    @Override
    public Integer removeDocument(List<Integer> ids) {
        List<Document> documents = documentMapper.selectBatchIds(ids);
        //数据库数量!=传入的实际数量
        if (documents.size() != ids.size()) {
            throw new ServiceException(RequestException.NOT_FOUND);
        }
        int column = documentMapper.deleteBatchIds(ids);
        if (column < 1) {
            throw new ServiceException(RequestException.DELETE_ERROR);
        }
        return column;
    }
}
